<template>
  <div class="admin-container">
    <!-- 布局容器 -->
    <el-container>
      <!-- 侧边栏 -->
      <el-aside :width="isCollapse ? '64px' : '260px'" class="admin-sidebar">
        <div class="sidebar-header">
          <div class="logo-container">
            <div class="logo">☁️</div>
            <transition name="fade">
              <div v-show="!isCollapse" class="logo-text">
                <h2>云梦智学</h2>
                <el-tag type="primary" size="small">管理控制台</el-tag>
              </div>
            </transition>
          </div>

          <!-- 折叠按钮移到logo区域 -->
          <div class="collapse-btn" @click="toggleCollapse">
            <el-icon>
              <Expand v-if="isCollapse" />
              <Fold v-else />
            </el-icon>
          </div>
        </div>

        <!-- 菜单 -->
        <el-menu :default-active="activeMenu" :collapse="isCollapse" :collapse-transition="false"
          background-color="#1e293b" text-color="rgba(255, 255, 255, 0.7)" active-text-color="#fff"
          @select="handleMenuSelect">
          <el-menu-item index="dashboard">
            <el-icon>
              <DataAnalysis />
            </el-icon>
            <span>数据总览</span>
          </el-menu-item>

          <el-menu-item index="users">
            <el-icon>
              <User />
            </el-icon>
            <span>用户管理</span>
          </el-menu-item>

          <el-menu-item index="questions">
            <el-icon>
              <Document />
            </el-icon>
            <span>题库管理</span>
          </el-menu-item>

          <el-menu-item index="knowledge">
            <el-icon>
              <Connection />
            </el-icon>
            <span>知识图谱</span>
          </el-menu-item>

          <el-sub-menu index="content">
            <template #title>
              <el-icon>
                <Grid />
              </el-icon>
              <span>内容管理</span>
            </template>
            <el-menu-item index="videos">
              <el-icon>
                <VideoPlay />
              </el-icon>
              <span>视频课程</span>
            </el-menu-item>
            <el-menu-item index="topics">
              <el-icon>
                <ChatDotRound />
              </el-icon>
              <span>话题社区</span>
            </el-menu-item>
            <el-menu-item index="pk">
              <el-icon>
                <Trophy />
              </el-icon>
              <span>PK竞赛</span>
            </el-menu-item>
          </el-sub-menu>

          <el-sub-menu index="system">
            <template #title>
              <el-icon>
                <Setting />
              </el-icon>
              <span>系统管理</span>
            </template>
            <el-menu-item index="reports">
              <el-icon>
                <TrendCharts />
              </el-icon>
              <span>数据报表</span>
            </el-menu-item>
            <el-menu-item index="settings">
              <el-icon>
                <Tools />
              </el-icon>
              <span>系统设置</span>
            </el-menu-item>
            <el-menu-item index="audit">
              <el-icon>
                <Search />
              </el-icon>
              <span>操作日志</span>
            </el-menu-item>
          </el-sub-menu>
        </el-menu>
      </el-aside>

      <!-- 主内容区 -->
      <el-container>
        <!-- 顶部导航 -->
        <el-header class="admin-header">
          <div class="header-left">
            <h1 class="page-title">{{ currentPageTitle }}</h1>
            <el-breadcrumb separator="/">
              <el-breadcrumb-item v-for="(item, index) in breadcrumbItems" :key="index">
                {{ item }}
              </el-breadcrumb-item>
            </el-breadcrumb>
          </div>

          <div class="header-right">
            <!-- 搜索框 -->
            <el-input v-model="searchText" placeholder="搜索功能..." prefix-icon="Search" class="header-search" clearable />

            <!-- 通知 -->
            <el-badge :value="notificationCount" class="notification-badge">
              <el-button :icon="Bell" circle />
            </el-badge>

            <!-- 用户信息 -->
            <el-dropdown>
              <div class="user-info">
                <el-avatar :size="36" class="user-avatar">管</el-avatar>
                <div class="user-detail">
                  <div class="user-name">管理员</div>
                  <div class="user-role">超级管理员</div>
                </div>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item icon="User">个人中心</el-dropdown-item>
                  <el-dropdown-item icon="Setting">设置</el-dropdown-item>
                  <el-dropdown-item icon="SwitchButton" divided>退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-header>

        <!-- 页面内容区 -->
        <el-main class="admin-main">
          <!-- 数据总览 -->
          <div v-show="activeMenu === 'dashboard'">
            <!-- 统计卡片 -->
            <el-row :gutter="20" class="stat-cards">
              <el-col :xs="24" :sm="12" :lg="6" v-for="stat in statsData" :key="stat.key">
                <el-card class="stat-card" :class="`stat-${stat.type}`">
                  <div class="stat-header">
                    <div class="stat-icon">{{ stat.icon }}</div>
                    <el-tag :type="stat.trend > 0 ? 'success' : 'danger'" size="small" effect="plain">
                      {{ stat.trend > 0 ? '+' : '' }}{{ stat.trend }}%
                    </el-tag>
                  </div>
                  <div class="stat-body">
                    <div class="stat-value">{{ stat.value.toLocaleString() }}</div>
                    <div class="stat-label">{{ stat.label }}</div>
                    <div class="stat-desc">{{ stat.desc }}</div>
                  </div>
                </el-card>
              </el-col>
            </el-row>

            <!-- 图表区域 -->
            <el-row :gutter="20" class="chart-row">
              <el-col :span="24">
                <el-card class="chart-card">
                  <template #header>
                    <div class="chart-header">
                      <span class="chart-title">用户活跃度趋势</span>
                      <el-radio-group v-model="chartPeriod" size="small">
                        <el-radio-button label="7">7天</el-radio-button>
                        <el-radio-button label="30">30天</el-radio-button>
                        <el-radio-button label="90">90天</el-radio-button>
                      </el-radio-group>
                    </div>
                  </template>
                  <div ref="activityChart" class="chart-container"></div>
                </el-card>
              </el-col>
            </el-row>

            <el-row :gutter="20" class="chart-row">
              <el-col :xs="24" :lg="12">
                <el-card class="chart-card">
                  <template #header>
                    <span class="chart-title">知识点完成率 TOP 10</span>
                  </template>
                  <div ref="knowledgeChart" class="chart-container"></div>
                </el-card>
              </el-col>
              <el-col :xs="24" :lg="12">
                <el-card class="chart-card">
                  <template #header>
                    <span class="chart-title">PK胜率分布</span>
                  </template>
                  <div ref="pkChart" class="chart-container"></div>
                </el-card>
              </el-col>
            </el-row>
          </div>

          <!-- 用户管理 -->
          <div v-show="activeMenu === 'users'">
            <el-card>
              <template #header>
                <div class="table-header">
                  <span class="table-title">用户列表</span>
                  <div class="table-actions">
                    <el-button :icon="Search">搜索</el-button>
                    <el-button type="primary" :icon="Plus">添加用户</el-button>
                  </div>
                </div>
              </template>

              <el-table :data="userData" stripe style="width: 100%" v-loading="tableLoading">
                <el-table-column label="用户信息" min-width="200">
                  <template #default="scope">
                    <div class="user-info-cell">
                      <el-avatar :size="36">{{ scope.row.name[0] }}</el-avatar>
                      <div class="user-text">
                        <div class="user-name">{{ scope.row.name }}</div>
                        <div class="user-email">{{ scope.row.email }}</div>
                      </div>
                    </div>
                  </template>
                </el-table-column>

                <el-table-column prop="role" label="角色" width="120">
                  <template #default="scope">
                    <el-tag :type="getRoleType(scope.row.role)">
                      {{ scope.row.role }}
                    </el-tag>
                  </template>
                </el-table-column>

                <el-table-column label="星级" width="150">
                  <template #default="scope">
                    <el-rate v-model="scope.row.stars" disabled />
                  </template>
                </el-table-column>

                <el-table-column prop="registerTime" label="注册时间" width="150" />

                <el-table-column prop="status" label="状态" width="100">
                  <template #default="scope">
                    <el-tag :type="getStatusType(scope.row.status)">
                      {{ scope.row.status }}
                    </el-tag>
                  </template>
                </el-table-column>

                <el-table-column label="操作" width="180" fixed="right">
                  <template #default="scope">
                    <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>

              <!-- 分页 -->
              <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]" :total="totalUsers" layout="total, sizes, prev, pager, next, jumper"
                class="pagination" />
            </el-card>
          </div>

          <!-- 其他页面内容 -->
          <div v-show="activeMenu === 'questions'">
            <el-card>
              <template #header>
                <span class="table-title">题库管理</span>
              </template>
              <el-empty description="题库管理功能开发中..." />
            </el-card>
          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as echarts from 'echarts'
import Sidebar from '@/components/Sidebar.vue'
import {
  DataAnalysis,
  User,
  Document,
  Connection,
  Grid,
  VideoPlay,
  ChatDotRound,
  Trophy,
  Setting,
  TrendCharts,
  Tools,
  Search,
  Expand,
  Fold,
  Bell,
  Plus
} from '@element-plus/icons-vue'

// 响应式数据
const isCollapse = ref(false)
const activeMenu = ref('dashboard')
const searchText = ref('')
const notificationCount = ref(5)
const chartPeriod = ref('7')
const tableLoading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const totalUsers = ref(100)

// 统计数据
const statsData = reactive([
  {
    key: 'users',
    type: 'primary',
    icon: '👥',
    label: '总用户数',
    value: 12547,
    trend: 12,
    desc: '较上月增长 1,423 位'
  },
  {
    key: 'questions',
    type: 'success',
    icon: '📝',
    label: '题库总数',
    value: 8329,
    trend: 8,
    desc: '本月新增 623 道'
  },
  {
    key: 'pk',
    type: 'warning',
    icon: '⚔️',
    label: '今日PK场次',
    value: 1256,
    trend: 25,
    desc: '活跃度历史新高'
  },
  {
    key: 'topics',
    type: 'danger',
    icon: '💬',
    label: '活跃话题数',
    value: 453,
    trend: -3,
    desc: '需要增加运营活动'
  }
])

// 用户数据
const userData = ref([
  {
    id: 1,
    name: '张三',
    email: 'zhang@example.com',
    role: '学生',
    stars: 5,
    registerTime: '2024-08-15',
    status: '活跃'
  },
  {
    id: 2,
    name: '李老师',
    email: 'li@example.com',
    role: '教师',
    stars: 3,
    registerTime: '2024-07-20',
    status: '活跃'
  },
  {
    id: 3,
    name: '王五',
    email: 'wang@example.com',
    role: '学生',
    stars: 2,
    registerTime: '2024-09-01',
    status: '待激活'
  }
])

// 图表实例
let activityChartInstance = null
let knowledgeChartInstance = null
let pkChartInstance = null

// 图表引用
const activityChart = ref(null)
const knowledgeChart = ref(null)
const pkChart = ref(null)

// 计算属性
const currentPageTitle = computed(() => {
  const titles = {
    dashboard: '数据总览',
    users: '用户管理',
    questions: '题库管理',
    knowledge: '知识图谱',
    videos: '视频课程',
    topics: '话题社区',
    pk: 'PK竞赛',
    reports: '数据报表',
    settings: '系统设置',
    audit: '操作日志'
  }
  return titles[activeMenu.value] || '数据总览'
})

// 方法
const toggleCollapse = () => {
  isCollapse.value = !isCollapse.value
}

const handleMenuSelect = (index) => {
  activeMenu.value = index
  if (index === 'dashboard') {
    nextTick(() => {
      initCharts()
    })
  }
}

const getRoleType = (role) => {
  const types = {
    '学生': 'primary',
    '教师': 'success',
    '管理员': 'warning'
  }
  return types[role] || 'info'
}

const getStatusType = (status) => {
  const types = {
    '活跃': 'success',
    '待激活': 'warning',
    '已禁用': 'danger'
  }
  return types[status] || 'info'
}

const handleEdit = (row) => {
  ElMessage.info(`编辑用户: ${row.name}`)
}

const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除用户 ${row.name} 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    ElMessage.success('删除成功')
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 初始化图表
const initCharts = () => {
  // 活跃度趋势图
  if (activityChart.value) {
    activityChartInstance = echarts.init(activityChart.value)
    const option = {
      tooltip: {
        trigger: 'axis'
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
      },
      yAxis: {
        type: 'value'
      },
      series: [{
        name: '活跃用户',
        type: 'line',
        smooth: true,
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0, color: 'rgba(99, 102, 241, 0.3)'
            }, {
              offset: 1, color: 'rgba(99, 102, 241, 0.05)'
            }]
          }
        },
        emphasis: {
          focus: 'series'
        },
        lineStyle: {
          color: '#6366f1',
          width: 2
        },
        itemStyle: {
          color: '#6366f1'
        },
        data: [3200, 3800, 3500, 4200, 4800, 5200, 4500]
      }]
    }
    activityChartInstance.setOption(option)
  }

  // 知识点完成率图表
  if (knowledgeChart.value) {
    knowledgeChartInstance = echarts.init(knowledgeChart.value)
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: ['Java基础', 'Spring', 'MySQL', 'Redis', 'Vue3']
      },
      yAxis: {
        type: 'value',
        max: 100
      },
      series: [{
        name: '完成率',
        type: 'bar',
        barWidth: '60%',
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0, color: '#6366f1'
            }, {
              offset: 1, color: '#a78bfa'
            }]
          },
          borderRadius: [8, 8, 0, 0]
        },
        data: [95, 88, 82, 75, 70]
      }]
    }
    knowledgeChartInstance.setOption(option)
  }

  // PK胜率分布图表
  if (pkChart.value) {
    pkChartInstance = echarts.init(pkChart.value)
    const option = {
      tooltip: {
        trigger: 'item'
      },
      legend: {
        bottom: '5%',
        left: 'center'
      },
      series: [{
        name: 'PK结果',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 20,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 65, name: '胜利', itemStyle: { color: '#10b981' } },
          { value: 25, name: '失败', itemStyle: { color: '#ef4444' } },
          { value: 10, name: '平局', itemStyle: { color: '#f59e0b' } }
        ]
      }]
    }
    pkChartInstance.setOption(option)
  }
}

// 监听图表周期变化
watch(chartPeriod, (newVal) => {
  // 这里可以根据新的周期重新加载数据
  ElMessage.info(`切换到${newVal}天数据`)
})

// 生命周期
onMounted(() => {
  // 初始化图表
  nextTick(() => {
    initCharts()
  })

  // 监听窗口变化
  window.addEventListener('resize', () => {
    activityChartInstance?.resize()
    knowledgeChartInstance?.resize()
    pkChartInstance?.resize()
  })
})
</script>

<style scoped>
.admin-container {
  height: 100vh;
  background: #f5f7fa;
}

/* 侧边栏样式 */
.admin-sidebar {
  background: linear-gradient(180deg, #1e293b 0%, #0f172a 100%);
  transition: width 0.3s;
  position: relative;
  box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1);
}

.sidebar-header {
  padding: 20px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  position: relative;
}

.logo-container {
  display: flex;
  align-items: center;
  gap: 12px;
}

.logo {
  width: 40px;
  height: 40px;
  background: linear-gradient(135deg, #6366f1, #8b5cf6);
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.5rem;
  flex-shrink: 0;
}

.logo-text h2 {
  font-size: 1.2rem;
  color: white;
  margin: 0 0 5px 0;
  font-weight: 600;
}

.collapse-btn {
  position: absolute;
  top: 20px;
  right: 15px;
  width: 28px;
  height: 28px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: rgba(255, 255, 255, 0.7);
  transition: all 0.3s;
  backdrop-filter: blur(10px);
}

.collapse-btn:hover {
  background: rgba(255, 255, 255, 0.2);
  color: white;
  transform: scale(1.1);
}

/* 顶部导航样式 */
.admin-header {
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 60px;
}

.header-left {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.page-title {
  font-size: 1.5rem;
  font-weight: 600;
  color: #1e293b;
  margin: 0;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.header-search {
  width: 250px;
}

.notification-badge {
  margin-top: 3px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
  cursor: pointer;
  padding: 5px 10px;
  border-radius: 8px;
  transition: background 0.3s;
}

.user-info:hover {
  background: #f5f7fa;
}

.user-avatar {
  background: linear-gradient(135deg, #6366f1, #8b5cf6);
  color: white;
  font-weight: 600;
}

.user-detail {
  text-align: left;
}

.user-name {
  font-size: 14px;
  font-weight: 600;
  color: #1e293b;
}

.user-role {
  font-size: 12px;
  color: #64748b;
}

/* 主内容区样式 */
.admin-main {
  padding: 20px;
  background: #f5f7fa;
}

/* 统计卡片样式 */
.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
}

.stat-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 3px;
}

.stat-primary::before {
  background: linear-gradient(90deg, #6366f1, #8b5cf6);
}

.stat-success::before {
  background: linear-gradient(90deg, #10b981, #34d399);
}

.stat-warning::before {
  background: linear-gradient(90deg, #f59e0b, #fbbf24);
}

.stat-danger::before {
  background: linear-gradient(90deg, #ef4444, #f87171);
}

.stat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.5rem;
  background: linear-gradient(135deg, rgba(99, 102, 241, 0.1), rgba(139, 92, 246, 0.1));
}

.stat-body {
  margin-top: 10px;
}

.stat-value {
  font-size: 2rem;
  font-weight: 700;
  color: #1e293b;
  margin-bottom: 5px;
}

.stat-label {
  color: #64748b;
  font-size: 0.9rem;
  margin-bottom: 10px;
}

.stat-desc {
  color: #94a3b8;
  font-size: 0.85rem;
}

/* 图表样式 */
.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  height: 100%;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-title {
  font-size: 1.1rem;
  font-weight: 600;
  color: #1e293b;
}

.chart-container {
  height: 350px;
}

/* 表格样式 */
.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-title {
  font-size: 1.1rem;
  font-weight: 600;
  color: #1e293b;
}

.table-actions {
  display: flex;
  gap: 10px;
}

.user-info-cell {
  display: flex;
  align-items: center;
  gap: 10px;
}

.user-text {
  display: flex;
  flex-direction: column;
}

.user-email {
  font-size: 12px;
  color: #94a3b8;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 过渡动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* Element Plus 样式覆盖 */
:deep(.el-card) {
  border-radius: 12px;
  border: none;
}

:deep(.el-card__header) {
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background: #f8f9fa;
  color: #64748b;
  font-weight: 600;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .header-search {
    width: 200px;
  }

  .header-right {
    gap: 15px;
  }

  .user-detail {
    display: none;
  }

  .stat-cards .el-col {
    margin-bottom: 15px;
  }

  .chart-container {
    height: 250px;
  }
}

@media (max-width: 480px) {
  .admin-header {
    padding: 0 15px;
  }

  .admin-main {
    padding: 15px;
  }

  .header-search {
    width: 150px;
  }

  .page-title {
    font-size: 1.2rem;
  }

  .table-actions {
    flex-direction: column;
    gap: 5px;
  }
}
</style>